// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections.Generic;
using System.Data;
using SnapObjects.Commons;

namespace SnapObjects.Data.Odbc
{
    public class OdbcHanaTypeMapper : TypeMapper
    {
        private readonly OdbcHanaStringTypeMapping _unboundedUnicodeString
            = new OdbcHanaStringTypeMapping("nvarchar", dbType: null, unicode: true);

        private readonly OdbcHanaStringTypeMapping _keyUnicodeString
            = new OdbcHanaStringTypeMapping("nvarchar", dbType: null, unicode: true, size: 450);

        private readonly OdbcHanaStringTypeMapping _unboundedAnsiString
            = new OdbcHanaStringTypeMapping("varchar", dbType: DbType.AnsiString);

        private readonly OdbcHanaStringTypeMapping _keyAnsiString
            = new OdbcHanaStringTypeMapping("varchar", dbType: DbType.AnsiString, unicode: false, size: 900);

        private readonly OdbcHanaByteArrayTypeMapping _unboundedBinary
            = new OdbcHanaByteArrayTypeMapping("varbinary");

        private readonly OdbcHanaByteArrayTypeMapping _keyBinary
            = new OdbcHanaByteArrayTypeMapping("varbinary(900)", dbType: DbType.Binary, size: 900);

        private readonly OdbcHanaBlobTypeMapping _blob
            = new OdbcHanaBlobTypeMapping("blob", dbType: DbType.Binary);

        private readonly IntTypeMapping _int = new IntTypeMapping("int", DbType.Int32);

        private readonly LongTypeMapping _long = new LongTypeMapping("bigint", DbType.Int64);

        private readonly ShortTypeMapping _short = new ShortTypeMapping("smallint", DbType.Int16);

        private readonly ByteTypeMapping _byte = new ByteTypeMapping("tinyint", DbType.Byte);

        private readonly BoolTypeMapping _bool = new BoolTypeMapping("boolean", DbType.Boolean);

        private readonly OdbcCharTypeMapping _char
            = new OdbcCharTypeMapping("char", dbType: DbType.AnsiString);

        private readonly OdbcHanaStringTypeMapping _fixedLengthUnicodeString
            = new OdbcHanaStringTypeMapping("nchar", dbType: DbType.String, unicode: true);

        private readonly OdbcHanaStringTypeMapping _variableLengthUnicodeString
            = new OdbcHanaStringTypeMapping("nvarchar", dbType: null, unicode: true);

        private readonly OdbcHanaStringTypeMapping _fixedLengthAnsiString
            = new OdbcHanaStringTypeMapping("char", dbType: DbType.AnsiString);

        private readonly OdbcHanaStringTypeMapping _variableLengthAnsiString
            = new OdbcHanaStringTypeMapping("varchar", dbType: DbType.AnsiString);

        private readonly OdbcLongStringTypeMapping _longVariableLengthAnsiString
            = new OdbcLongStringTypeMapping("long varchar", dbType: DbType.AnsiString);

        private readonly OdbcHanaByteArrayTypeMapping _fixedLengthBinary = new OdbcHanaByteArrayTypeMapping("binary");

        private readonly OdbcHanaDateTimeTypeMapping _date = new OdbcHanaDateTimeTypeMapping("date", dbType: DbType.Date);

        private readonly OdbcHanaDateTimeTypeMapping _datetime = new OdbcHanaDateTimeTypeMapping("datetime", dbType: DbType.DateTime);

        private readonly OdbcFloatTypeMapping _float = new OdbcFloatTypeMapping("float", DbType.Single);

        private readonly OdbcDoubleTypeMapping _double = new OdbcDoubleTypeMapping("double", DbType.Double);

        private readonly OdbcDateTimeOffsetTypeMapping _datetimeoffset = new OdbcDateTimeOffsetTypeMapping("datetimeoffset");

        private readonly DecimalTypeMapping _decimal = new DecimalTypeMapping("decimal", DbType.Decimal);

        private readonly OdbcTimeSpanTypeMapping _time = new OdbcTimeSpanTypeMapping("time", DbType.Time);

        protected Dictionary<string, TypeMapping> _dbTypeMappings;

        protected Dictionary<Type, TypeMapping> _clrTypeMappings;

        protected HashSet<string> _disallowedMappings;

        public OdbcHanaTypeMapper(IDataContextOptions options) : base(options)
        {
            _dbTypeMappings = new Dictionary<string, TypeMapping>(StringComparer.OrdinalIgnoreCase)
            {
                //Boolean type
                { "boolean", _bool },
                //Datetime types 
                { "date", _date },
                { "time", _time },
                { "timestamp", _datetime },
                { "seconddate", _datetime},
                //Numeric types
                { "tinyint", _byte },
                { "smallint", _short },
                { "int", _int },
                { "integer", _int },
                { "bigint", _decimal },
                { "smalldecimal", _decimal },
                { "decimal", _decimal },
                { "real", _float },
                { "double", _double },
                //Character string types 
                { "char", _char},
                { "nchar", _fixedLengthUnicodeString},
                { "varchar", _variableLengthAnsiString },
                { "nvarchar", _variableLengthUnicodeString },
                { "alphanum", _longVariableLengthAnsiString },
                { "shorttext", _fixedLengthAnsiString },
                //Binary types 
                { "varbinary", _fixedLengthBinary },
                //Large Object types
                { "blob", _blob },
                { "clob", _variableLengthAnsiString},
                { "nclob", _variableLengthUnicodeString },
                { "text", _longVariableLengthAnsiString },
            };

            // Note: sbyte, ushort, uint, char and ulong type mappings are not supported by SQL Server.
            // We would need the type conversions feature to allow this to work - see https://github.com/aspnet/EntityFramework/issues/242.
            _clrTypeMappings = new Dictionary<Type, TypeMapping>
            {
                { typeof(int), _int },
                { typeof(long), _long },
                { typeof(DateTime), _datetime },
                { typeof(bool), _bool },
                { typeof(byte), _byte },
                { typeof(double), _double },
                { typeof(float), _float },
                { typeof(DateTimeOffset), _datetimeoffset },
                { typeof(short), _short },
                { typeof(decimal), _decimal },
                { typeof(TimeSpan), _time },
                { typeof(char), _char }
            };

            // These are disallowed only if specified without any kind of length specified in parenthesis.
            // This is because we don't try to make a new type from this string and any max length value
            // specified in the model, which means use of these strings is almost certainly an error, and
            // if it is not an error, then using, for example, varbinary(1) will work instead.
            _disallowedMappings = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
            {
            };

            this.ByteArrayMapper = new ByteArrayTypeMapper(
               maxBoundedLength: 8000,
               defaultMapping: _unboundedBinary,
               unboundedMapping: _unboundedBinary,
               keyMapping: _keyBinary,
               createBoundedMapping: size => new OdbcHanaByteArrayTypeMapping(
                   "varbinary(" + size + ")",
                   DbType.Binary,
                   size));

            this.StringMapper = new StringTypeMapper(
                maxBoundedAnsiLength: 8000,
                defaultAnsiMapping: _unboundedAnsiString,
                unboundedAnsiMapping: _unboundedAnsiString,
                keyAnsiMapping: _keyAnsiString,
                createBoundedAnsiMapping: size => new OdbcHanaStringTypeMapping(
                    "varchar(" + size + ")",
                    DbType.AnsiString,
                    unicode: false,
                    size: size),
                maxBoundedUnicodeLength: 4000,
                defaultUnicodeMapping: _unboundedUnicodeString,
                unboundedUnicodeMapping: _unboundedUnicodeString,
                keyUnicodeMapping: _keyUnicodeString,
                createBoundedUnicodeMapping: size => new OdbcHanaStringTypeMapping(
                    "nvarchar(" + size + ")",
                    dbType: null,
                    unicode: true,
                    size: size));
        }

        public override IByteArrayTypeMapper ByteArrayMapper { get; }

        public override IStringTypeMapper StringMapper { get; }

        public override void ValidateTypeName(string dbTypeName)
        {
            if (_disallowedMappings.Contains(dbTypeName))
            {
                throw new ArgumentException(OdbcStrings.UnqualifiedDataType(dbTypeName));
            }
        }

        public override TypeMapping FindMapping(Type clrType)
        {
            Check.NotNull(clrType, nameof(clrType));

            clrType = TypeHelper.UnwrapEnumType(TypeHelper.UnwrapNullableType(clrType));

            return clrType == typeof(string)
                ? _unboundedUnicodeString
                : (clrType == typeof(byte[]) ? _unboundedBinary : base.FindMapping(clrType));
        }

        protected override IReadOnlyDictionary<Type, TypeMapping> GetClrTypeMappings()
        {
            return _clrTypeMappings;
        }

        protected override IReadOnlyDictionary<string, TypeMapping> GetDbTypeMappings()
        {
            return _dbTypeMappings;
        }
    }
}
